from fisheye_manager import FisheyeManager
from location_manager import LocationManager
from traffic_manager import TrafficManager
import fisheye_consts
import sys
import os
import shutil


def initialize_consts(tm):
    """
    Initializes the constants according to the input traffic file.
    """
    fisheye_consts.FISHEYE_MAX_LINK_DISTANCE = tm.get_reception_radius()
    fisheye_consts.FISHEYE_NODE_CELL_POWER = tm.get_power()
    fisheye_consts.FISHEYE_MESSAGE_QUEUE_CAPACITY = tm.get_queue_size()

def main():
    """
    USAGE : python main.py [TRAFFIC FILEPATH] [LOCATIONS FILEPATH]
    """
    if len(sys.argv) == 3:
        TRAFFIC_FILENAME = sys.argv[1]
        LOCATIONS_FILENAME = sys.argv[2]
        print "Running according to given file paths : \r\n%s\r\n%s" %  (TRAFFIC_FILENAME, LOCATIONS_FILENAME)

    else:
        LOCATIONS_FILENAME = "location.txt"
        TRAFFIC_FILENAME = "traffic.txt"
        print "Defaulting to local files in the running directory - %s,%s" % (TRAFFIC_FILENAME, LOCATIONS_FILENAME)

    print "Reading locations..."
    lm = LocationManager(LOCATIONS_FILENAME)
    
    print "Reading traffic..."
    tm = TrafficManager(TRAFFIC_FILENAME)
    
    if lm.get_number_of_ticks() != tm.get_number_of_ticks():
        print "The number of steps in the location and traffic files are different!"
        sys.exit(1)
    
    print "Starting simulation..."
    initialize_consts(tm)
    fm = FisheyeManager(lm, tm)

    #Initialize working dirs :
    trafficFilename = os.path.basename(TRAFFIC_FILENAME)
    locationsFilename = os.path.basename(LOCATIONS_FILENAME)
    tm.DIRNAME = fm.DIRNAME = "%s_%s" % (os.path.splitext(trafficFilename)[0],
                                         os.path.splitext(locationsFilename)[0])
    if os.path.exists(fm.DIRNAME):
        shutil.rmtree(fm.DIRNAME)

    os.mkdir(fm.DIRNAME)


    fm.initialize_nodes()
    
    ticks = lm.get_number_of_ticks()

    fm.init_packets_info_file()
    fm.init_steps_info_file()

    for i in xrange(ticks):
        print "Tick number", i
        fm.run_one_step()

    fm.calc_packets_latency()

    print "Finished simulation!"

if __name__ == "__main__":
    main()
